package com.oner365.test.socket.keepalive;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LongConnectionClient {

  private static final Logger LOGGER = LoggerFactory.getLogger(LongConnectionClient.class);

  private static ExecutorService executorService = Executors.newSingleThreadExecutor();
  
  public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    Socket socket = connectionServer(InetAddress.getLocalHost(), 8884);
   
    Callable<Boolean> callable = () ->{
      int index = 1;
      while(true) {
        TimeUnit.SECONDS.sleep(2);
        String data = "传入数据"+index+"次";
        writeData(socket,data);
        index++;
        String responseBody = readData(socket);
        LOGGER.info("客户端收到:{}", responseBody);
        if(index == 10) {
          writeData(socket,"shutdown");
          break;
        }
      }
      return false;
    };
    Future<Boolean> future = executorService.submit(callable);
    if(!future.get()) {
      // 关闭资源
      LOGGER.info("链接关闭");
      socket.shutdownInput();
      socket.shutdownOutput();
      socket.close();
      executorService.shutdown();
      
    }
  }
  
  public static Socket connectionServer(InetAddress inetAddress,Integer prot ) {
    try {
      return new Socket(inetAddress, prot);
    } catch (IOException e) {
      LOGGER.error("connectionServer error:",e);
      return null;
    }
  }
  
  public static void writeData(Socket socket,String data) {
    OutputStream outputStream;
    try {
      outputStream = socket.getOutputStream();
      outputStream.write(data.getBytes());
    } catch (IOException e) {
      LOGGER.error("writeData error:",e);
    }
  }
  
  public static String readData(Socket socket) {
    InputStream inputStream;
    try {
      inputStream = socket.getInputStream();
      byte[] buf = new byte[1024];
      int length = inputStream.read(buf);
      return new String(buf, 0, length);
    } catch (IOException e) {
      LOGGER.error("readData error:",e);
      return null;
    }
  }

}
